import { ResPage, TreeNode } from '@/api/interface'
import { Menu } from './interface'
import { UC } from '@/api/config/servicePort'
import http from '@/api'

// 树型菜单
export function treeMenus(query?: Menu.Query) {
  return http.get<ResPage<TreeNode>>(UC + '/menu/tree', query ? query : { pageable: false })
}

// 树型选项菜单
export function treeMenuOption(appcode?: string) {
  return http.get<TreeNode[]>(UC + '/menu/option/tree', { appcode })
}

// 上级属性树型菜单
export function fetchParentTree(appcode?: string) {
  return http.get<TreeNode[]>(UC + '/menu/parent/tree', { appcode }, { loading: false })
}

// 获取排序号
export function getSortOrder(id: string) {
  return http.get<number>(UC + '/menu/sort', { id }, { loading: false })
}

// 检查权限是否存在
export function checkPermissionExist(permission: string, id?: string) {
  return http.get<boolean>(UC + '/menu/permission/exist', { permission, id }, { loading: false })
}

// 检查名称是否存在
export function checkNameExist(name: string, id?: string) {
  return http.get<boolean>(UC + '/menu/name/exist', { name, id }, { loading: false })
}

// 检查应用编码是否存在
export function checkAppcodeExist(appcode: string, id?: string) {
  return http.get<boolean>(UC + '/menu/appcode/exist', { appcode, id }, { loading: false })
}

// 新增菜单
export const addMenu = (params: Partial<Menu.Form>) => {
  return http.post(UC + '/menu', params)
}

// 菜单详情
export const getMenu = (id: string) => {
  return http.get<Partial<Menu.Form>>(UC + '/menu', { id }, { loading: false })
}

// 编辑
export const updateMenu = (params: Partial<Menu.Form>) => {
  return http.put(UC + '/menu', params)
}

// 删除
export const removeMenu = (id: string) => {
  return http.delete(UC + '/menu', { id })
}

// 获取当前用户菜单
export async function fetchCurrentUserMenus(appcode: string) {
  try {
    const { data } = await http.get<Menu.Record[]>(UC + '/menu/current', { appcode })
    return data ? data : []
  } catch (e) {
    return []
  }
}
